<template>
  <div class="status-configuration-panel">
    <a-row :gutter="16">
      <!-- 状态定义管理 -->
      <a-col :span="12">
        <a-card title="状态定义管理" size="small">
          <template #extra>
            <a-button
              type="primary"
              size="small"
              @click="
                () => {
                  showCreateStatusModal = true;
                }
              "
            >
              <template #icon>
                <IconifyIcon icon="ant-design:plus-outlined" />
              </template>
              新建状态
            </a-button>
          </template>

          <a-table
            :columns="statusColumns"
            :data-source="statusDefinitions"
            :pagination="false"
            size="small"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'color'">
                <a-tag :color="record.color">{{ record.name }}</a-tag>
              </template>
              <template v-else-if="column.key === 'type'">
                <a-tag v-if="record.isInitial" color="green">初始</a-tag>
                <a-tag v-else-if="record.isFinal" color="red">终态</a-tag>
                <a-tag v-else color="default">普通</a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button
                    type="link"
                    size="small"
                    @click="editStatus(record)"
                  >
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个状态定义吗？"
                    @confirm="deleteStatus(record.id)"
                  >
                    <a-button type="link" size="small" danger>删除</a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 状态转换规则 -->
      <a-col :span="12">
        <a-card title="状态转换规则" size="small">
          <template #extra>
            <a-button
              type="primary"
              size="small"
              @click="
                () => {
                  showCreateRuleModal = true;
                }
              "
            >
              <template #icon>
                <IconifyIcon icon="ant-design:plus-outlined" />
              </template>
              新建规则
            </a-button>
          </template>

          <a-table
            :columns="ruleColumns"
            :data-source="transitionRules"
            :pagination="false"
            size="small"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'from'">
                <a-tag v-for="status in record.from" :key="status" color="blue">
                  {{ getStatusLabel(status) }} ({{ status }})
                </a-tag>
              </template>
              <template v-else-if="column.key === 'to'">
                <a-tag color="green">{{ getStatusLabel(record.to) }}</a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button type="link" size="small" @click="editRule(record)">
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个转换规则吗？"
                    @confirm="deleteRule(record.id)"
                  >
                    <a-button type="link" size="small" danger>删除</a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 状态定义编辑模态框 -->
    <a-modal
      :open="showCreateStatusModal"
      :title="editingStatus ? '编辑状态定义' : '新建状态定义'"
      @ok="saveStatus"
      @cancel="
        () => {
          showCreateStatusModal = false;
          resetStatusForm();
        }
      "
    >
      <a-form
        ref="statusFormRef"
        :model="statusForm"
        :rules="statusRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="状态名称" name="name">
              <a-input
                v-model:value="statusForm.name"
                placeholder="请输入状态名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态代码" name="code">
              <a-input
                v-model:value="statusForm.code"
                placeholder="请输入状态代码"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="statusForm.description"
            placeholder="请输入状态描述"
            :rows="3"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="颜色" name="color">
              <a-input v-model:value="statusForm.color" placeholder="#1890ff" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="图标" name="icon">
              <a-input
                v-model:value="statusForm.icon"
                placeholder="ant-design:check-circle"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="状态类型">
              <a-space>
                <a-checkbox v-model:checked="statusForm.isInitial"
                  >初始状态</a-checkbox
                >
                <a-checkbox v-model:checked="statusForm.isFinal"
                  >终态</a-checkbox
                >
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 转换规则编辑模态框 -->
    <a-modal
      :open="showCreateRuleModal"
      :title="editingRule ? '编辑转换规则' : '新建转换规则'"
      @ok="saveRule"
      @cancel="
        () => {
          showCreateRuleModal = false;
          resetRuleForm();
        }
      "
    >
      <a-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        layout="vertical"
      >
        <a-form-item label="起始状态" name="from">
          <a-select
            v-model:value="ruleForm.from"
            mode="multiple"
            placeholder="选择起始状态"
            style="width: 100%"
          >
            <a-select-option
              v-for="status in statusDefinitions"
              :key="status.code"
              :value="status.code"
            >
              {{ status.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="目标状态" name="to">
          <a-select
            v-model:value="ruleForm.to"
            placeholder="选择目标状态"
            style="width: 100%"
          >
            <a-select-option
              v-for="status in statusDefinitions"
              :key="status.code"
              :value="status.code"
            >
              {{ status.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="转换条件" name="conditions">
          <a-textarea
            v-model:value="ruleForm.conditions"
            placeholder="请输入转换条件（可选）"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="转换动作" name="actions">
          <a-textarea
            v-model:value="ruleForm.actions"
            placeholder="请输入转换动作（可选）"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  configUpdated: [];
}>();

// 响应式数据
const showCreateStatusModal = ref(false);
const showCreateRuleModal = ref(false);
const editingStatus = ref<any>(null);
const editingRule = ref<any>(null);

// 状态定义数据
const statusDefinitions = ref([
  {
    id: '1',
    name: '待审核',
    code: 'PENDING_REVIEW',
    description: '资源等待审核状态',
    color: '#faad14',
    icon: 'ant-design:clock-circle-outlined',
    isInitial: true,
    isFinal: false,
  },
  {
    id: '2',
    name: '已审核',
    code: 'APPROVED',
    description: '资源审核通过状态',
    color: '#52c41a',
    icon: 'ant-design:check-circle-outlined',
    isInitial: false,
    isFinal: false,
  },
  {
    id: '3',
    name: '已拒绝',
    code: 'REJECTED',
    description: '资源审核拒绝状态',
    color: '#ff4d4f',
    icon: 'ant-design:close-circle-outlined',
    isInitial: false,
    isFinal: true,
  },
]);

// 转换规则数据
const transitionRules = ref([
  {
    id: '1',
    from: ['PENDING_REVIEW'],
    to: 'APPROVED',
    conditions: '审核通过',
    actions: '发送通知',
  },
  {
    id: '2',
    from: ['PENDING_REVIEW'],
    to: 'REJECTED',
    conditions: '审核拒绝',
    actions: '发送拒绝通知',
  },
]);

// 表单数据
const statusFormRef = ref();
const statusForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  color: '#1890ff',
  icon: '',
  isInitial: false,
  isFinal: false,
});

const ruleFormRef = ref();
const ruleForm = reactive({
  id: '',
  from: [] as string[],
  to: '',
  conditions: '',
  actions: '',
});

// 表单验证规则
const statusRules = {
  name: [{ required: true, message: '请输入状态名称' }],
  code: [{ required: true, message: '请输入状态代码' }],
};

const ruleRules = {
  from: [{ required: true, message: '请选择起始状态' }],
  to: [{ required: true, message: '请选择目标状态' }],
};

// 表格列定义
const statusColumns = [
  { title: '状态名称', dataIndex: 'name', key: 'name' },
  { title: '状态代码', dataIndex: 'code', key: 'code' },
  { title: '显示', key: 'color' },
  { title: '类型', key: 'type' },
  { title: '操作', key: 'action', width: 120 },
];

const ruleColumns = [
  { title: '起始状态', key: 'from' },
  { title: '目标状态', key: 'to' },
  { title: '条件', dataIndex: 'conditions', key: 'conditions' },
  { title: '操作', key: 'action', width: 120 },
];

// 方法
const editStatus = (record: any) => {
  editingStatus.value = record;
  Object.assign(statusForm, record);
  showCreateStatusModal.value = true;
};

const deleteStatus = async (id: string) => {
  try {
    statusDefinitions.value = statusDefinitions.value.filter(
      (item) => item.id !== id,
    );
    message.success('删除成功');
    emit('configUpdated');
  } catch (error) {
    message.error('删除失败');
  }
};

const saveStatus = async () => {
  try {
    await statusFormRef.value.validate();

    if (editingStatus.value) {
      const index = statusDefinitions.value.findIndex(
        (item) => item.id === editingStatus.value.id,
      );
      if (index !== -1) {
        statusDefinitions.value[index] = { ...statusForm };
      }
      message.success('状态定义更新成功');
    } else {
      const newStatus = {
        ...statusForm,
        id: Date.now().toString(),idid
      };
      statusDefinitions.value.push(newStatus);
      message.success('状态定义创建成功');
    }

    showCreateStatusModal.value = false;
    resetStatusForm();
    emit('configUpdated');
  } catch (error) {
    message.error('保存失败');
  }
};

const resetStatusForm = () => {
  editingStatus.value = null;
  statusFormRef.value?.resetFields();
  Object.assign(statusForm, {
    id: '',
    name: '',
    code: '',
    description: '',
    color: '#1890ff',
    icon: '',
    isInitial: false,
    isFinal: false,
  });
};

const editRule = (record: any) => {
  editingRule.value = record;
  Object.assign(ruleForm, record);
  showCreateRuleModal.value = true;
};

const deleteRule = async (id: string) => {
  try {
    transitionRules.value = transitionRules.value.filter(
      (item) => item.id !== id,
    );
    message.success('删除成功');
    emit('configUpdated');
  } catch (error) {
    message.error('删除失败');
  }
};

const saveRule = async () => {
  try {
    await ruleFormRef.value.validate();

    if (editingRule.value) {
      const index = transitionRules.value.findIndex(
        (item) => item.id === editingRule.value.id,
      );
      if (index !== -1) {
        transitionRules.value[index] = { ...ruleForm };
      }
      message.success('转换规则更新成功');
    } else {
      const newRule = {
        ...ruleForm,
        id: Date.now().toString(),idid
      };
      transitionRules.value.push(newRule);
      message.success('转换规则创建成功');
    }

    showCreateRuleModal.value = false;
    resetRuleForm();
    emit('configUpdated');
  } catch (error) {
    message.error('保存失败');
  }
};

const resetRuleForm = () => {
  editingRule.value = null;
  ruleFormRef.value?.resetFields();
  Object.assign(ruleForm, {
    id: '',
    from: [],
    to: '',
    conditions: '',
    actions: '',
  });
};

// 状态标签转换方法
const getStatusLabel = (statusCode: string) => {
  const statusLabels: Record<string, string> = {
    PENDING_REVIEW: '待审核',
    APPROVED: '已审核',
    REJECTED: '已拒绝',
    ACTIVE: '已激活',
    SUSPENDED: '已暂停',
    ARCHIVED: '已归档',
    DRAFT: '草稿',
    STAGED: '已暂存',
    CANARY: '金丝雀',
    DEPRECATED: '已废弃',
    ROLLED_BACK: '已回滚',
    AVAILABLE: '可用',
    RESERVED: '已预订',
    IN_USE: '使用中',
    UNAVAILABLE: '不可用',
    FAILED: '故障',
  };
  return statusLabels[statusCode] || statusCode;
};

// 初始化
onMounted(() => {
  // 这里可以加载实际的状态配置数据
});
</script>

<style lang="less" scoped>
.status-configuration-panel {
  .ant-table {
    .ant-table-tbody > tr > td {
      padding: 8px;
    }
  }
}
</style>
